<?php

namespace app\api\controller;

use app\common\model\Enum;
use think\facade\Validate;
use think\facade\Request;
use think\Db;
use think\facade\Log;
use app\api\model\HttpMachine;

/**
 * 洗衣机刷卡支付. 独立出来, 是为了将来可以迁移到 go语言去并发够生猛
 * Class Order
 * @package app\api\controller\user
 */
class Wash extends Controller
{
    /**
     * http://cardwash.chubangkj.com/api/wash/cardWash?machinesn=254275&rfid=CC7CACA5&action=kuaixi
     * 学生卡洗衣
     * @param $user_id
     * @param $order
     * @return bool
     * @throws \Exception
     */
   


    public function cardWash()
    {
        $machineNo = Request::param("machinesn");
        $card_no = Request::param("rfid");
        $action = Request::param("action");

        //测试修改api期间. 这里要做个东西来记录刷卡成功;
        
        $time2 =date('Y-m-d H:i:s',time());
        $data=[
            'machine_no' => $machineNo,
            'card_no' => $card_no,
            'create_at' => $time2,
            'action' =>$action,
        ];
        $errid = Db::table('cardwash_log')->strict(false)->insertGetId($data);
        // return $this->renderSuccess_200("success");

        $wint = Enum::GetWashInt($action);
        if($wint == -1){
            return $this->renderError_400("error command",$errid);
        }

        $machine = Db::table('machine')->where("machine_no",$machineNo)->find();
        if(!$machine){
            return $this->renderError_400("machine not exist",$errid);
        }

        // $re=HttpMachine::SendWashCammand($machineNo,$action);
        // Log::write('order_type_card-'.$re);
        // $data['back_remark']=$re;

        // {"err_code":400,"err_msg":"253982 - CC7CACA5- kuaixi- {\"success\":1,\"msg\":\"ok\",\"data\":{\"online\":\"1\",\"runningstatus\":\"2\",\"runningprocess\":\"3\",\"runningprogram\":\"2\",\"remainingtime\":\"24\",\"faultflag\":\"\"}}"}

        // $re=HttpMachine::SendWashCammand($machineNo,"workstatus");
        // return $this->renderError_400("$machineNo - $card_no- $action- $re");

        $re = HttpMachine::GetMachineWorkStatus($machineNo);
        if($re == ""){
            return $this->renderError_400("execute command fail",$errid);
        }
        if($re != "1"){
            return $this->renderError_400("please change one",$errid);
        }

        
        $map=[
            ['card_no', '=', $card_no],
            ['status', '=', Enum::BindCard_SUCESS]
        ];
        $bindcard = Db::table('bindcard')->where($map)->find();
        if(!$bindcard){
            return $this->renderError_400("card not match user",$errid);
        }

        $amount=0;
        $map=[
            ['wash_type', '=', $wint],
            ['area_id', '=', $machine['area_id']]
        ];
        $price = Db::table('price')->where($map)->find();
        if(!$price){
            return $this->renderError_400("price is empty",$errid);
        }
        $amount=$price["wash_price"]*100;


        $user = Db::table('user')->where("id",$bindcard['user_id'])->find();
        if(!$user){
            return $this->renderError_400("user is empty",$errid);
        }

        if($amount > $user['amount']){
            return $this->renderError_400("amount not enough",$errid);
        }

        $no = Enum::orderNo(Enum::order_type_card);
        $time =date('Y-m-d H:i:s',time());
        $n_amount = ($user['amount'] - $amount);

        $data=[
            'user_id' => $user['id'],
            'apsid' => $user['apsid'],
            'open_id' => '',
            'union_id' => '',
            'order_no' => $no,
            'create_at' => $time,
            'update_at' => $time,
            'trade_no' => "",
            'card_no' => $card_no,
            'machine_no' => $machineNo,
            'type' => Enum::b_type_card,
            'area_id' => $machine['area_id'],
            'amount' => $amount,
            'wash_type' => $action,
            'pay_status' => Enum::PAY_SUCESS,
            'pay_channel' => 0
        ];

        $book=[
            'user_id' => $user['id'],
            'b_type' => Enum::b_type_card,
            'b_id' => 0,
            'b_no' => $no,
            'create_at' => $time,
            'old_amount' =>$user['amount'],
            'var_amount' => -1 * $amount ,
            'amount' => $n_amount
        ];

        $re=HttpMachine::SendWashCammand($machineNo,$action);
        $data['wash_status']=$re;

        Db::startTrans();
        try {
            $id=Db::table('order')->strict(false)->insertGetId($data);
            if($id>0){
                //扣用户的钱
                $c = Db::table('user')->where('id',$user['id'])->setDec('amount',$amount); //->update(['amount' => $n_amount]);
                if($c >0){
                    //记录流水账
                    $book['b_id']=$id;
                    Db::table('daybook')->strict(false)->insert($book);
                }
				
				Db::table('cardwash_log')->where('id',$errid)->update(['msg' => 'ok','cammand' => $re,'order_id'=>$id]);
				
                Db::commit();
            }else{
                Db::rollback();
                return $this->renderError_400("db fail",$errid);
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError_400("db fail",$errid);
        }
        return $this->renderSuccess_200("success");



    }



}
